package 常见算法查找;

public class 二分查找 {
    public static void main(String[] args) {
        //二分查找/折半查找
        //核心：
        //每次排除一半的查找范围

        //需求：定义一个方法利用二分查找，查询某个元素在数组中的索引
        //数据如下：{7, 23, 79, 81, 103, 127, 131, 147}
        int[] arr = {7, 23, 79, 81, 103, 127, 131, 147};
        System.out.println(BinarySearch(arr, 145));
    }

    public static int BinarySearch(int[] arr, int number) {//二分查找
        int hig = arr.length - 1;
        int low = 0;
        while (true) {
            if (low > hig) {
                return -1;
            }
            int mid = (hig + low) / 2;
            if (arr[mid] > number) {
                hig = mid - 1;
            } else if (arr[mid] < number) {
                low = mid + 1;
            } else {
                return mid;
            }
        }
    }
}
